/**
 *  JFTSTool - Java Full Text Search tool.
 *  Copyright (C) <2009>  <grupo JFTS>
 *  This program is free software: you can redistribute it and/or modify
 *	it under the terms of the GNU General Public License as published by
 *	the Free Software Foundation, either version 3 of the License, or
 *	(at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.jftstool.analyzers.filtersFactory;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.WordlistLoader;
import org.jftstool.analyzers.exceptions.FilterException;


/**
 * Factory that returns a filter stemmer.
 * @author grupo JFTS
 *
 */
public class StemmerFilterFactory implements IFilterFactory{
		private Set<Object> exceptionsTable = new HashSet<Object>();
	
	
	@Override
	public TokenStream create(TokenStream input, Map<String, String> args) throws FilterException {
		String stemmerClass = args.get("stemmer");
		boolean ignoreCase = Boolean.parseBoolean(args.get("ignoreCase"));
		
		TokenFilter dinamicFilter = null;
		
		String exceptionsListFile = args.get("stemmerExceptions");
	
		File file = new File(exceptionsListFile);
		if (file.exists()){
			_setExceptionsTable(file);
		}		

		if (stemmerClass != null && !stemmerClass.equals("")){
			try {
				Class<? extends TokenFilter> filterClass;
				filterClass = Class.forName(stemmerClass).asSubclass(TokenFilter.class);
				
				if (exceptionsTable.isEmpty()){
					Constructor<? extends TokenFilter> c = filterClass.getConstructor(TokenStream.class, boolean.class);
					dinamicFilter = c.newInstance(input, ignoreCase);					
				}
				else{
					Constructor<? extends TokenFilter> c = filterClass.getConstructor(TokenStream.class, Set.class, boolean.class);
					dinamicFilter = c.newInstance(input, exceptionsTable, ignoreCase);
				}
			}
			catch (Exception e) {
				throw new FilterException("Error, cant't dinamic instantiate class: " + stemmerClass);
			}
		}
		return dinamicFilter;
	}
	
	
	@SuppressWarnings("unchecked")	
	private void _setExceptionsTable(File file) throws FilterException {
		try {
			exceptionsTable = new HashSet<Object>(WordlistLoader.getWordSet(file));
		}
		catch (IOException e) {
			throw new FilterException("Cant't load stopWords file: " + file.getAbsolutePath());
		}
	}	
}